import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'index.dart';
import '../../../common/values/images.dart';

/// 登录页面视图
/// 
/// 现代简洁风格的登录界面，采用清新色调
/// 包含用户名密码表单、记住密码功能
class LoginPage extends GetView<LoginController> {
  const LoginPage({super.key});

  // 主视图构建方法
  Widget _buildView() {
    return _buildModernBackground(
      child: Center(
        child: SingleChildScrollView(
          padding: const EdgeInsets.symmetric(horizontal: 24.0),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              _buildHeader(),
              const SizedBox(height: 60),
              _buildLoginForm(),
              const SizedBox(height: 40),
              _buildFooter(),
            ],
          ),
        ),
      ),
    );
  }

  /// 构建现代风格背景
  Widget _buildModernBackground({required Widget child}) {
    return Container(
      width: double.infinity,
      height: double.infinity,
      decoration: const BoxDecoration(
        gradient: LinearGradient(
          begin: Alignment.topLeft,
          end: Alignment.bottomRight,
          colors: [
            Color(0xFFF8F9FA),
            Color(0xFFE9ECEF),
            Color(0xFFF8F9FA),
          ],
          stops: [0.0, 0.5, 1.0],
        ),
      ),
      child: CustomPaint(
        painter: ModernBackgroundPainter(),
        child: child,
      ),
    );
  }

  // 构建页面头部
  Widget _buildHeader() {
    return Column(
      children: [
        _buildLogo(),
        const SizedBox(height: 32),
        _buildTitle(),
        const SizedBox(height: 16),
        _buildSubtitle(),
      ],
    );
  }

  // 构建Logo
  Widget _buildLogo() {
    return Container(
      width: 100,
      height: 100,
      decoration: BoxDecoration(
        shape: BoxShape.circle,
        color: Colors.white,
        boxShadow: [
          BoxShadow(
            color: const Color(0xFF2C3E50).withOpacity(0.2),
            blurRadius: 20,
            offset: const Offset(0, 8),
          ),
        ],
      ),
      child: ClipOval(
        child: Padding(
          padding: const EdgeInsets.all(15),
          child: Image.asset(
            AssetsImages.logoPng,
            width: 70,
            height: 70,
            fit: BoxFit.contain,
            errorBuilder: (context, error, stackTrace) {
              // 如果图片加载失败，显示默认图标
              debugPrint('登录页面Logo加载失败: $error');
              return Container(
                width: 70,
                height: 70,
                alignment: Alignment.center,
                child: const Icon(
                  Icons.account_circle,
                  size: 50,
                  color: Color(0xFF2C3E50),
                ),
              );
            },
          ),
        ),
      ),
    );
  }

  // 构建标题
  Widget _buildTitle() {
    return Text(
      controller.welcomeText,
      textAlign: TextAlign.center,
      style: const TextStyle(
        fontSize: 28,
        fontWeight: FontWeight.bold,
        color: Color(0xFF2C3E50),
        letterSpacing: 1.5,
        height: 1.2,
      ),
    );
  }

  // 构建副标题
  Widget _buildSubtitle() {
    return Text(
      controller.subtitleText,
      textAlign: TextAlign.center,
      style: TextStyle(
        fontSize: 16,
        color: const Color(0xFF2C3E50).withOpacity(0.7),
        letterSpacing: 0.5,
      ),
    );
  }

  // 构建登录表单
  Widget _buildLoginForm() {
    return Container(
      width: double.infinity,
      constraints: const BoxConstraints(maxWidth: 400),
      padding: const EdgeInsets.all(32),
      decoration: BoxDecoration(
        color: Colors.white.withOpacity(0.9),
        borderRadius: BorderRadius.circular(20),
        boxShadow: [
          BoxShadow(
            color: const Color(0xFF2C3E50).withOpacity(0.1),
            blurRadius: 30,
            offset: const Offset(0, 15),
          ),
        ],
      ),
      child: Form(
        key: controller.formKey,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            _buildPhoneField(),
            const SizedBox(height: 20),
            _buildCaptchaField(),
            const SizedBox(height: 32),
            _buildLoginButton(),
            // 错误信息显示
            if (controller.hasError.value) ...[
              const SizedBox(height: 16),
              _buildErrorMessage(),
            ],
          ],
        ),
      ),
    );
  }

  // 构建手机号输入框
  Widget _buildPhoneField() {
    return TextFormField(
      controller: controller.phoneController,
      focusNode: controller.phoneFocusNode,
      keyboardType: TextInputType.phone,
      maxLength: 11, // 限制手机号最多11位
      validator: (value) {
        if (value == null || value.isEmpty) {
          return '请输入手机号';
        }
        if (!RegExp(r'^1[3-9]\d{9}$').hasMatch(value)) {
          return '请输入有效的手机号';
        }
        return null;
      },
      onChanged: controller.onPhoneChanged,
      decoration: InputDecoration(
        labelText: '手机号',
        hintText: '请输入手机号',
        prefixIcon: const Icon(
          Icons.phone_outlined,
          color: Color(0xFF2C3E50),
        ),
        border: OutlineInputBorder(
          borderRadius: BorderRadius.circular(12),
          borderSide: BorderSide(color: Colors.grey.shade300),
        ),
        focusedBorder: OutlineInputBorder(
          borderRadius: BorderRadius.circular(12),
          borderSide: const BorderSide(color: Color(0xFF2C3E50), width: 2),
        ),
        enabledBorder: OutlineInputBorder(
          borderRadius: BorderRadius.circular(12),
          borderSide: BorderSide(color: Colors.grey.shade300),
        ),
        errorBorder: OutlineInputBorder(
          borderRadius: BorderRadius.circular(12),
          borderSide: const BorderSide(color: Colors.red),
        ),
        filled: true,
        fillColor: Colors.white,
      ),
      onFieldSubmitted: (_) {
        controller.captchaFocusNode.requestFocus();
      },
    );
  }

  // 构建验证码输入框（带获取验证码按钮）
  Widget _buildCaptchaField() {
    return Row(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        // 验证码输入框
        Expanded(
          child: TextFormField(
            controller: controller.captchaController,
            focusNode: controller.captchaFocusNode,
            keyboardType: TextInputType.number,
            maxLength: 6, // 限制验证码最多6位
      validator: (value) {
        if (value == null || value.isEmpty) {
                return '请输入验证码';
        }
              if (value.length != 6) {
                return '验证码应为6位';
        }
        return null;
      },
            onChanged: controller.onCaptchaChanged,
      decoration: InputDecoration(
              labelText: '验证码',
              hintText: '请输入6位验证码',
        prefixIcon: const Icon(
                Icons.verified_user_outlined,
          color: Color(0xFF2C3E50),
        ),
        border: OutlineInputBorder(
          borderRadius: BorderRadius.circular(12),
          borderSide: BorderSide(color: Colors.grey.shade300),
        ),
        focusedBorder: OutlineInputBorder(
          borderRadius: BorderRadius.circular(12),
          borderSide: const BorderSide(color: Color(0xFF2C3E50), width: 2),
        ),
        enabledBorder: OutlineInputBorder(
          borderRadius: BorderRadius.circular(12),
          borderSide: BorderSide(color: Colors.grey.shade300),
        ),
        errorBorder: OutlineInputBorder(
          borderRadius: BorderRadius.circular(12),
          borderSide: const BorderSide(color: Colors.red),
        ),
        filled: true,
        fillColor: Colors.white,
      ),
      onFieldSubmitted: (_) {
        controller.onLoginTap();
      },
          ),
        ),
        const SizedBox(width: 12),
        // 获取验证码按钮
        _buildGetCodeButton(),
      ],
    );
  }

  // 构建获取验证码按钮
  Widget _buildGetCodeButton() {
    return SizedBox(
      height: 56,
      child: ElevatedButton(
        onPressed: (controller.countdown.value > 0 || controller.isSendingCode.value)
            ? null
            : controller.sendVerificationCode,
        style: ElevatedButton.styleFrom(
          backgroundColor: const Color(0xFF2C3E50),
          foregroundColor: Colors.white,
          disabledBackgroundColor: Colors.grey.shade300,
          disabledForegroundColor: Colors.grey.shade600,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(12),
          ),
          padding: const EdgeInsets.symmetric(horizontal: 16),
          elevation: 2,
        ),
        child: controller.isSendingCode.value
            ? const SizedBox(
                width: 16,
                height: 16,
                child: CircularProgressIndicator(
                  strokeWidth: 2,
                  valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
                ),
              )
            : Text(
                controller.countdown.value > 0
                    ? '${controller.countdown.value}s'
                    : '获取验证码',
                style: const TextStyle(
            fontSize: 14,
                  fontWeight: FontWeight.w500,
                ),
          ),
        ),
    );
  }

  // 构建登录按钮
  Widget _buildLoginButton() {
    return SizedBox(
      height: 50,
      child: ElevatedButton(
        onPressed: controller.isLoading.value ? null : controller.onLoginTap,
        style: ElevatedButton.styleFrom(
          backgroundColor: const Color(0xFF2C3E50),
          foregroundColor: Colors.white,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(12),
          ),
          elevation: 2,
        ),
        child: controller.isLoading.value
            ? const SizedBox(
                width: 20,
                height: 20,
                child: CircularProgressIndicator(
                  strokeWidth: 2,
                  valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
                ),
              )
            : const Text(
                '登 录',
                style: TextStyle(
                  fontSize: 16,
                  fontWeight: FontWeight.w600,
                  letterSpacing: 2,
                ),
        ),
      ),
    );
  }

  /// 构建错误信息
  Widget _buildErrorMessage() {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
      decoration: BoxDecoration(
        color: Colors.red.withOpacity(0.1),
        borderRadius: BorderRadius.circular(8),
        border: Border.all(
          color: Colors.red.withOpacity(0.3),
          width: 1,
        ),
      ),
      child: Row(
        children: [
          Icon(
            Icons.error_outline,
            color: Colors.red.withOpacity(0.8),
            size: 16,
          ),
          const SizedBox(width: 8),
          Expanded(
            child: Text(
              controller.errorMessage.value,
              style: TextStyle(
                color: Colors.red.withOpacity(0.9),
                fontSize: 14,
              ),
            ),
          ),
        ],
      ),
    );
  }

  // 构建页面底部
  Widget _buildFooter() {
    return Column(
      children: [
        Text(
          '© 2025 专家评审系统',
          style: TextStyle(
            fontSize: 12,
            color: const Color(0xFF2C3E50).withOpacity(0.5),
          ),
        ),
        const SizedBox(height: 8),
        Text(
          '在线评审系统 v1.0.0',
          style: TextStyle(
            fontSize: 10,
            color: const Color(0xFF2C3E50).withOpacity(0.4),
          ),
        ),
      ],
    );
  }


  @override
  Widget build(BuildContext context) {
    // 设置状态栏样式 - 浅色背景使用深色图标
    SystemChrome.setSystemUIOverlayStyle(
      const SystemUiOverlayStyle(
        statusBarColor: Colors.transparent,
        statusBarIconBrightness: Brightness.dark,
        statusBarBrightness: Brightness.light,
        systemNavigationBarColor: Colors.white,
        systemNavigationBarIconBrightness: Brightness.dark,
      ),
    );
    
    return GetBuilder<LoginController>(
      // 不要使用 init，让它使用 Binding 中注册的实例
      id: "login",
      builder: (_) {
        return Scaffold(
          backgroundColor: const Color(0xFFF8F9FA),
          // 无AppBar，全屏显示
          body: SafeArea(
            child: _buildView(),
          ),
        );
      },
    );
  }
}

/// 现代背景绘制器
class ModernBackgroundPainter extends CustomPainter {
  @override
  void paint(Canvas canvas, Size size) {
    final paint = Paint()
      ..style = PaintingStyle.fill;

    // 绘制简洁的几何图案
    paint.color = const Color(0xFF2C3E50).withOpacity(0.02);
    
    // 绘制一些圆形装饰
    for (int i = 0; i < 15; i++) {
      final x = (size.width * (i * 0.15)) % size.width;
      final y = (size.height * (i * 0.23)) % size.height;
      final radius = (i % 4 + 1) * 20.0;
      
      canvas.drawCircle(Offset(x, y), radius, paint);
    }
    
    // 绘制一些线条装饰
    paint.strokeWidth = 1;
    paint.style = PaintingStyle.stroke;
    
    for (int i = 0; i < 8; i++) {
      final startX = size.width * (i * 0.12);
      final startY = size.height * 0.1;
      final endX = size.width * ((i + 1) * 0.12);
      final endY = size.height * 0.9;
      
      canvas.drawLine(
        Offset(startX, startY),
        Offset(endX, endY),
        paint,
      );
    }
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) => false;
}
